package cn.unknowpupil.init.service.system.impl;


import cn.unknowpupil.init.common.constant.ScheduleConstants;
import cn.unknowpupil.init.configure.quartz.ScheduleUtils;
import cn.unknowpupil.init.domain.system.SysJob;

import cn.unknowpupil.init.exceptions.TaskException;
import cn.unknowpupil.init.mapper.system.SysJobMapper;
import cn.unknowpupil.init.service.system.ISysJobService;
import cn.unknowpupil.init.utils.strings.StringUtils;
import cn.unknowpupil.init.utils.quartz.CronUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务调度信息 服务层
 *
 * @author unknowpupil
 */

/**
 * Created at 2020-11-06 by  w10g <br>
 * Initialize SysJob  ... <br>
 * 定时任务调度表 核心业务处理实现类
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {
    @Resource
    private Scheduler scheduler;


    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        log.info("初始化所有定时任务-----------------");
        scheduler.clear();
        List<SysJob> jobList = baseMapper.selectList(null);
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * @param current {@code int} 页码
     * @param size    {@code int} 笔数
     * @param sysJob  {@link SysJob}
     * @return 调度任务集合
     */
    @Override
    public IPage<SysJob> page(int current, int size, SysJob sysJob) {
        IPage<SysJob> page = new Page<>(current, size);
        LambdaQueryWrapper<SysJob> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(sysJob.getJobName())) {
            wrapper.like(SysJob::getJobName, sysJob.getJobName());
        }
        if (StringUtils.isNotBlank(sysJob.getJobGroup())) {
            wrapper.eq(SysJob::getJobGroup, sysJob.getJobGroup());
        }
        if (StringUtils.isNotBlank(sysJob.getStatus())) {
            wrapper.like(SysJob::getStatus, sysJob.getStatus());
        }
        if (StringUtils.isNotBlank(sysJob.getInvokeTarget())) {
            wrapper.like(SysJob::getInvokeTarget, sysJob.getInvokeTarget());
        }
        return super.page(page, wrapper);
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(Long jobId) {
        return baseMapper.selectById(jobId);
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        int rows = baseMapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJob job = baseMapper.selectById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException, TaskException {
        int rows = 0;
        Trigger.TriggerState triggerState = scheduler.getTriggerState(ScheduleUtils.getTriggerKey(job.getId(), job.getJobGroup()));

        if (triggerState == Trigger.TriggerState.NONE) {
            log.info("【重置定时任务】-----------------没有此类定时任务，重新添加{}",job.toString());
            ScheduleUtils.createScheduleJob(scheduler, job);
        }

        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(SysJob job) throws SchedulerException, TaskException {
        Trigger.TriggerState triggerState = scheduler.getTriggerState(ScheduleUtils.getTriggerKey(job.getId(), job.getJobGroup()));
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getId());
        if (triggerState == Trigger.TriggerState.NONE) {
            log.info("【重置定时任务】-----------------没有此类定时任务，重新添加{}",properties.toString());
            ScheduleUtils.createScheduleJob(scheduler, properties);
        }
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = baseMapper.insert(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        SysJob properties = selectJobById(job.getId());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = job.getId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }
}
